package base.thread.pools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPools {

    //包含一个阻塞队列，用来组织任务
    public BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //这个list就用来存放当前的工作线程.
    public List<Thread> works = new ArrayList<>();

    public int MAX_WORKER_COUNT = 10;

    //通过这个方法，把任务加入到线程池中
    //submit不光可以把任务放到阻塞队列中，也可以负责创建线程
    public void submit(Runnable command) throws IOException, InterruptedException {
        System.out.println("size = " + works.size());
        if (works.size() < MAX_WORKER_COUNT) {
            //如果当前工作线程的数量不足线程数目上线，就创建出新的线程
            //工作线程就专门找一个类完成
            //worker内部要哦能够取到队列的内容，就要把这个队列实例通过worker的构造方法传过去
            MyWorkerThread worker = new MyWorkerThread(queue);
            worker.start();
            works.add(worker);
        }
        queue.put(command);
    }



    public static void main (String[] args) throws IOException, InterruptedException {
        MyThreadPools threadPoll = new MyThreadPools();

        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPoll.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("hello i = " + finalI + ";threadName = " + Thread.currentThread().getName());
                }
            });
        }

    }


}
